package model

import (
	"github.com/hajimehoshi/ebiten/v2"
	"time"
)

type Coin struct {
	*Entity
	Coins []*Coin
}

const (
	coinInterval = 1 * time.Second // 金币生成间隔
)

var (
	lastCoinTime time.Time // 上次生成金币的时间
	coinCount    int       // 当前金币数量
)

func NewCoin(config *Config) *Coin {
	path := "static/img/coin.png"
	coin := &Coin{
		Entity: NewEntity(path),
		Coins:  []*Coin{},
	}
	coin.X = float64(config.ScreenWidth)
	coin.Y = float64(config.ScreenHeight - coin.Height*3)
	return coin
}

func (c *Coin) CreateCoin(config *Config) {
	// 更新金币的位置并移除超出屏幕的金币
	var updatedCoins []*Coin
	for _, coin := range c.Coins {
		coin.X -= float64(config.BgSpeedFactor)
		if coin.X > -float64(coin.Width) {
			updatedCoins = append(updatedCoins, coin)
		}
	}
	c.Coins = updatedCoins
	// 更新金币数量
	coinCount = len(c.Coins)

	currentTime := time.Now()
	// 生成金币
	if coinCount < config.MaxCoins && currentTime.Sub(lastCoinTime) >= coinInterval/5 {
		coin := NewCoin(config)
		c.Coins = append(c.Coins, coin)
		lastCoinTime = currentTime
		coinCount++

	}

}

func (c *Coin) Draw(screen *ebiten.Image) {
	// 绘制金币
	for _, coin := range c.Coins {
		coin.DrawScreen(screen)
	}
}
